package com.zc.serviceuser.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.zc.commonutils.Result;
import com.zc.feign.clients.LogClient;
import com.zc.feign.clients.UserClient;
import com.zc.serviceuser.Interceptor.UserHolder;
import com.zc.serviceuser.entity.User;
import com.zc.serviceuser.entity.dto.LoginFormDTO;
import com.zc.serviceuser.entity.dto.LoginFormDTOTwo;
import com.zc.serviceuser.entity.dto.UserDTO;
import com.zc.serviceuser.entity.dto.registerFormDTO;
import com.zc.serviceuser.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private LogClient logClient;

    @Resource
   private UserClient userClient;

    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone) {
        //  发送短信验证码并保存验证码
        return userClient.getCode(phone);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody @Valid registerFormDTO registerFormDTO)  {
       return userService.register(registerFormDTO);
    }

    /**
     * 第一种登录方式
     * @param loginForm
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("/login")
    public Result login(@RequestBody @Valid LoginFormDTO loginForm) throws JsonProcessingException {

       return userService.login(loginForm);


    }

    @PostMapping("/loginTwo")
    public Result loginTwo(@RequestBody @Valid LoginFormDTOTwo loginFormDTOTwo) throws JsonProcessingException {


       return userService.loginTwo(loginFormDTOTwo);
    }


    @PostMapping("/readExcel")
    public Result readExcel(@RequestParam("file") MultipartFile file){
       return userService.readExcel(file,userService);

    }

    @GetMapping("/writeExcel/{description}")
    public void wireExcel(@PathVariable("description") String description, HttpServletResponse response){
        userService.wireExcel(description,response);
    }

    @GetMapping("/getAllUser")
    public Result getAllUser(){
        List<User> list = userService.list();
        return Result.ok().data("list",list);
    }

//    @GetMapping("/getAllUserByUser")
//    public Result getAllUserByUser(){
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("name","phone","description");
//        List<User> list = userService.list(queryWrapper);
//        return Result.ok().data("list",list);
//    }


    //根据id删除用户
    @DeleteMapping("{id}")
    public Result removeUser(@PathVariable("id") String id){
        boolean flag = userService.removeById(id);
        return flag ? Result.ok():Result.error();
    }

    //根据id删除多个用户
    @PostMapping("deleteByIds")
    public Result removeUsers(@RequestBody List<String> arr){
        boolean flag = userService.removeByIds(arr);
        return flag ? Result.ok():Result.error();
    }

    //分页查询
    @GetMapping("getAllUser/{current}/{limit}")
    public Result pageListTeacher(@PathVariable("current") long current,
                                @PathVariable("limit") long limit){
        Page<User> pageUser = new Page<>(current,limit);
        UserDTO user = UserHolder.getUser();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("creat_time");
       if ("2".equals(user.getRole())){
           userService.page(pageUser, queryWrapper);
       }else {
           queryWrapper.select("user_name","phone","description");
           userService.page(pageUser, queryWrapper);
       }

        long total = pageUser.getTotal();

        List<User> records = pageUser.getRecords();

        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("data",records);
        return Result.ok().data(map);
    }


    //条件查询带分页
    @GetMapping("pageUserCondition/{current}/{limit}/{name}")
    public Result pageTeacherCondition(@PathVariable("current") long current,
                                  @PathVariable("limit") long limit,
                                  @PathVariable("name") String name) {
        Page<User> page = new Page<>(current,limit);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        UserDTO user = UserHolder.getUser();

        if ("1".equals(user.getRole())){
            wrapper.select("id","user_name","phone","description");
        }
        wrapper.like(!StringUtils.isEmpty(name),"user_name",name);
        //排序
        wrapper.orderByAsc("creat_time");
        userService.page(page,wrapper);
        long total = page.getTotal();
        List<User> records = page.getRecords();
        return Result.ok().data("total",total).data("data",records);
    }


    @PostMapping("addUser")
    public Result addUser(@RequestBody User user) {
        boolean b = userService.saveOrUpdate(user);
        if (b) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    //根据讲师id查询用户信息
    @GetMapping("getUser/{id}")
    public Result getTecher(@PathVariable("id") String id){
        User user = userService.getById(id);
        return Result.ok().data("user",user);
    }


    //根据id修改
    @PutMapping("updateUser")
    public Result updateTeacher(@RequestBody User user){
        boolean flag = userService.updateById(user);
        return flag ? Result.ok() : Result.error();
    }

//登出功能
    @PostMapping("/logout")
    public Result logout(){
        UserHolder.removeUser();
        return Result.ok();
    }




}
